import React, { useEffect, useState, useMemo } from "react";
import { Button, Select, Steps, theme, Typography } from "antd";
const { Title } = Typography;
import { Checkbox, Form, Input } from "antd";
import axios from "axios";
import NewsEditor from "../../../components/news-manage/NewsEditor";
import { useNavigate } from "react-router-dom";
import { notification } from "antd";
import { Map } from "immutable";
//富文本编辑器 使用Draft Wysiwyg

//content属性就是步骤的内容属性
const steps = [
  {
    title: "基本信息",
    description: "新闻标题 新闻分类",
  },
  {
    title: "新闻内容",
    description: "撰写新内容",
  },
  {
    title: "提交新闻",
    description: "保存草稿或者提交审核",
  },
];
export default function NewsAdd() {
  /* steps步骤栏所需函数与状态 */
  const [current, setCurrent] = useState(0);
  const { token } = theme.useToken();
  const next = () => {
    // 校验第一部表单是否填写
    if (current == 0) {
      // 校验新闻标题是否填写
      if (!newsTitle || !newsCategory) {
        alert("请填写完整信息");
        return;
      }
    } else if (current == 1) {
      //如果没有填写内容
      if (news.content === "" || news.content === "<p></p>\n") {
        alert("请填写内容");
        return;
      }
    }
    setCurrent(current + 1);
  };
  const prev = () => {
    setCurrent(current - 1);
  };
  const items = steps.map((item) => ({ key: item.title, title: item.title }));
  const contentStyle = {
    color: token.colorTextTertiary,
    backgroundColor: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    border: `1px dashed ${token.colorBorder}`,
    marginTop: 16,
  };

  /* step 0 表单所需函数 */
  // 设置newsTitle与newsCategory 后续设置newsContent来保存
  const [newsTitle, setNewsTitle] = useState("");
  const [newsCategory, setNewsCategory] = useState("");
  const [categoryList, setCategoryList] = useState([]);
  // 创建Map用于名称和ID的映射
  useEffect(() => {
    axios.get("http://localhost:3000/categories").then((res) => {
      // 设置列表数据
      const formattedData = res.data.map((item) => ({
        //设置value和lable的原因就是antd的设计原则就是label和value对应 在渲染的时候向外展示label 内部函数则提供value 如果不这样设置就默认使用value
        label: item.title,
        value: item.id,
      }));
      setCategoryList(formattedData);
    });
  }, []);
  //handleChange用于处理选择框变化时将选择的值赋值给newsCategory
  const handleChange = (value) => {    
    // value已经是ID了，直接设置
    setNewsCategory(value);
  };

  /* step 1 表单所需函数与状态 */
  const [newsContent, setNewsContent] = useState("");

  /* step 2 表单所需函数与状态 */
  // 整合新闻信息 提交新闻
  /* 方案一 使用setNews() 函数  但是会造成状态更新，导致组件重新渲染，从而导致无限循环 所以需要使用useEffect
    // 使用 useEffect 来更新 news 状态，避免无限重渲染
    原因:
    组件首次渲染 → 执行到 setNews() → 触发状态更新状态更新 → 组件重新渲染 → 再次执行到 setNews() → 又触发状态更新
    无限循环 → 2 → 2 → 2 → ...
  
  const [news, setNews] = useState({});
  useEffect(() => {
    setNews({
      title: newsTitle,
      categoryId: newsCategory,
      content: newsContent,
    });
  }, [newsTitle, newsCategory, newsContent]); 
  */
  // 推荐方法：使用 useMemo 计算派生状态
  const news = useMemo(
    () => ({
      title: newsTitle,
      categoryId: newsCategory,
      content: newsContent,
    }),
    [newsTitle, newsCategory, newsContent]
  );

  /* step 3 表单所需函数与状态 */
  const navigator = useNavigate();
  const user = JSON.parse(localStorage.getItem("token"));
  const handleSave = (auditState) => {
    axios
      .post(" http://localhost:3000/news", {
        ...news,
        region: user.region ? user.region : "全球",
        author: user.username,
        roleId: user.roleId,
        auditState: auditState,
        publishState: 0, //审核状态
        createTime: Date.now(),
        star: 0, //点赞
        view: 0, //浏览
        publishTi0me: 0, //未发布
      })
      .then(() => {
        // 请求成功后显示通知
        openNotification("bottomRight", auditState);
        // 然后跳转页面
        if (auditState === 0) navigator("/news-manage/draft");
        else navigator("/audit-manage/list");
      })
      .catch((error) => {
        // 请求失败时显示错误通知
        api.error({
          message: "操作失败",
          description: "保存新闻时发生错误，请重试",
          placement: "bottomRight",
        });
        console.error("Save error:", error);
      });
  };
  //通知栏
  const [api, contextHolder] = notification.useNotification();
  const openNotification = (placement, auditState) => {
    api.success({
      message: auditState === 0 ? "保存成功" : "提交成功",
      description: `您可以在${
        auditState === 0 ? "草稿箱" : "审核列表"
      }中查看您的新闻`,
      placement,
      duration: 3,
    });
  };

  //content编写
  steps[0].content = (
    <Form
      name="basic"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ maxWidth: 600, marginTop: "30px" }}
      initialValues={{ remember: true }}
      autoComplete="off"
    >
      <Form.Item
        label="新闻标题"
        name="title"
        rules={[{ required: true, message: "请输入新闻标题!" }]}
      >
        {/* 设置成可控组件 后续可以通过newsTitle来获取输入的新闻标题 */}
        <Input
          value={newsTitle}
          onChange={(e) => setNewsTitle(e.target.value)}
          defaultValue={newsTitle}
        />
      </Form.Item>

      <Form.Item
        label="新闻分类"
        name="categoryId"
        rules={[{ required: true, message: "请选择新闻分类!" }]}
      >
        <Select
          showSearch
          options={categoryList}
          onChange={handleChange}
          defaultValue={newsCategory}
        />
      </Form.Item>
    </Form>
  );
  //content编写
  steps[1].content = (
    <NewsEditor
      getContent={(value) => {
        setNewsContent(value);
      }}
    />
  );
  //content编写
  steps[2].content = <></>;
  return (
    <div>
      {contextHolder}
      <Title>攥写新闻</Title>
      <Steps current={current} items={items} />
      <div style={contentStyle}>{steps[current].content}</div>
      <div style={{ marginTop: 24 }}>
        {/* 确保下一步不会出现在最后的步骤 */}
        {current < steps.length - 1 && (
          <Button
            htmlType="submit"
            onClick={() => {
              next();
            }}
          >
            下一步
          </Button>
        )}
        {current === steps.length - 1 && (
          <>
            <Button
              type="primary"
              onClick={() => {
                handleSave(0);
              }}
            >
              保存草稿
            </Button>
            <Button
              type="primary"
              danger
              onClick={() => {
                handleSave(1);
              }}
            >
              提交审核
            </Button>
          </>
        )}
        {current > 0 && (
          <Button style={{ margin: "0 8px" }} onClick={() => prev()}>
            上一步
          </Button>
        )}
      </div>
    </div>
  );
}
